from django.db import models
from django.utils.translation import ugettext_lazy as _

class Asset(models.Model):
    title = models.CharField(_('title'), max_length=100)
    file = models.FileField(upload_to='assets/%Y/%m/%d')
    date_added = models.DateTimeField(auto_now_add=True)
    mimetype = models.CharField(editable=False, null=True, max_length=50)
    
    def _get_mimetype(self):
        import mimetypes
        type, encoding = mimetypes.guess_type(self.file.path)
        return type
    
    def __unicode__(self):
        return self.title
    
    def get_absolute_url(self):
        return self.file.url
    
    def asset_link(self, text=None):
        if text is None:
            text = self.file.name
        return '<a href="%s">%s</a>' % (self.get_absolute_url(), text)
    asset_link.allow_tags = True
    asset_link.short_description = 'Path'
    
    def save(self, **options):
        self.mimetype = self._get_mimetype()
        
        super(Asset, self).save(**options)
